package com.senseauto.camerarecorder;

import androidx.appcompat.app.AppCompatActivity;

import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback{
    private static final String TAG = "MainActivity";
    private SurfaceView mSurfaceView;
    private Button mRecordBtn, mPlayBtn;
    private boolean mIsRecord = false; //是否正在录像
    private Camera mCamera;
    private MediaRecorder mMediaRecorder;
    private String mMediaPath;
    private SurfaceHolder mSurfaceHolder;
    private int cameraId = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSurfaceView = (SurfaceView) findViewById(R.id.surface);
        mSurfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // 必须-设置Surface不需要维护自己的缓冲区
        mRecordBtn = (Button) findViewById(R.id.btnRecord);
        if(getIntent()!=null){
            String cameraIdStr = getIntent().getStringExtra("dmsCameraID");
            Log.e(TAG, "cameraIdStr="+cameraIdStr);
            if(!TextUtils.isEmpty(cameraIdStr)){
                cameraId = Integer.parseInt(cameraIdStr);
            }
        }
        SurfaceHolder holder = mSurfaceView.getHolder();
        holder.addCallback(this);
        mRecordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mIsRecord) {
                    try {
                        Log.d(TAG, "首次点击开始录像 ");
                        if (prepareVideoRecorder()) {
                            mMediaRecorder.start();
                            mIsRecord = true;
                            mRecordBtn.setText("stop");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.d(TAG, "再次点击停止录像 "+mMediaPath);
                    mMediaRecorder.stop();
                    releaseMediaRecorder();
                    mCamera.lock();
                    mRecordBtn.setText("record");
                    mIsRecord = false;
                    if (mCamera != null) {
                        mCamera.release();
                        mCamera = null;
                    }
                }
            }
        });

    }


    private boolean prepareVideoRecorder() throws IOException {
        if (mMediaRecorder == null) {
            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.reset();
        }
        /*camera相关设置部分*/
        mCamera = Camera.open(cameraId);//Camera.CameraInfo.CAMERA_FACING_BACK
        if (mCamera != null) {
            //设置旋转角度，顺时针方向，因为默认是逆向90度的，这样图像就是正常显示了
            //mCamera.setDisplayOrientation(90);
            mCamera.unlock();
            mMediaRecorder.setCamera(mCamera);
        }
        /*recorder设置部分*/
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        mMediaRecorder.setOutputFile(getOutputMediaFile());
        mMediaRecorder.setPreviewDisplay(mSurfaceView.getHolder().getSurface());
        mMediaRecorder.prepare();
        return true;
    }

    private String getDate() {
        Log.d(TAG, "获取录制视频的日期 ");
        SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.CHINA);
        return format.format(new Date()) ;
    }
    /*
     *创建视频存储文件夹 录制好的视频存储在手机外部存储中 以录像时间+mp4格式命名
     * */
    private String getOutputMediaFile() {
        Log.d(TAG, "获取视频存储的位置 ");
        String mediaPath = getExternalCacheDir().getPath();
        if (mediaPath != null) {
            File mediaFile = new File(mediaPath , "videos");
            if (!mediaFile.exists()) {
                mediaFile.mkdir();
            }
            return mMediaPath = mediaFile.getAbsolutePath() + File.separator + getDate() + ".mp4";
        }
        return null;
    }
    /*
     * 录制视频结束时释放相机资源
     * */
    private void releaseMediaRecorder() {
        Log.d(TAG, "录制结束后释放资源 ");
        if (mMediaRecorder != null) {
            mMediaRecorder.reset(); // clear recorder configuration
            mMediaRecorder.release(); // release the recorder object
            mMediaRecorder = null;
            mCamera.lock();   // lock camera for later use
        }
    }
    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        mSurfaceHolder = surfaceHolder;
    }
    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        mSurfaceHolder = surfaceHolder;
    }
    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mSurfaceView = null;
        mSurfaceHolder = null;
        releaseMediaRecorder();
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }

    }
}